function carousel(options) {
  const $selector = this
  let activeIndex = options.index || 0
  const timeout = options.timeout || 5000
  const trigger = options.trigger === 'hover'
    ? 'mouseenter'
    : 'click'

  let $pics = $selector.find('.move .pic')
  let $circles = $selector.find('.choice .circle')
  $pics.eq(activeIndex).show()
  $circles.eq(activeIndex).addClass('change')

  function toggleNextItem(direction) {
    if (direction === 'prev') {
      activeIndex--
      if (activeIndex < 0) {
        activeIndex = $pics.length - 1
      }
    } else {
      activeIndex++
      if (activeIndex >= $pics.length) {
        activeIndex = 0
      }
    }
    $pics.eq(activeIndex).stop().fadeIn()
      .siblings().stop().fadeOut()
    $circles.eq(activeIndex).addClass('change')
      .siblings().removeClass('change')
  }

  let timer = setInterval(function () {
    toggleNextItem()
  }, timeout)

  $selector.hover(function () {
    // paused
    clearInterval(timer)
  }, function () {
    // run
    timer = setInterval(function () {
      toggleNextItem()
    }, timeout)
  })

  $selector.find('.r-arrow').on('click', function () {
    toggleNextItem('next')
  })

  $selector.find('.l-arrow').on('click', function () {
    toggleNextItem('prev')
  })

  $circles.on(trigger, function () {
    activeIndex = $(this).index()
    $pics.eq(activeIndex).stop().fadeIn()
      .siblings().stop().fadeOut()
    $circles.eq(activeIndex).addClass('change')
      .siblings().removeClass('change')
  })
}

$.fn.carousel = carousel
